#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <thread>
#include <chrono>
#include <atomic>
#include <iomanip>

// 获取CPU核心数
unsigned int get_cpu_cores() {
    return std::thread::hardware_concurrency();
}

// 读取/proc/stat文件，获取CPU时间
std::vector<unsigned long long> read_cpu_times() {
    std::ifstream proc_stat("/proc/stat");
    std::string line;
    std::vector<unsigned long long> cpu_times;

    // 读取第一行（总CPU时间）
    if (std::getline(proc_stat, line)) {
        std::istringstream iss(line);
        std::string cpu_label;
        iss >> cpu_label; // 跳过"cpu"标签
        unsigned long long time;
        while (iss >> time) {
            cpu_times.push_back(time);
        }
    }

    return cpu_times;
}

// 计算CPU占用率
double calculate_cpu_usage(const std::vector<unsigned long long>& prev_times,
                           const std::vector<unsigned long long>& curr_times) {
    unsigned long long prev_idle = prev_times[3]; // idle时间
    unsigned long long curr_idle = curr_times[3];

    unsigned long long prev_total = 0;
    unsigned long long curr_total = 0;

    for (size_t i = 0; i < prev_times.size(); ++i) {
        prev_total += prev_times[i];
        curr_total += curr_times[i];
    }

    unsigned long long total_diff = curr_total - prev_total;
    unsigned long long idle_diff = curr_idle - prev_idle;

    if (total_diff == 0) {
        return 0.0;
    }

    return 100.0 * (1.0 - static_cast<double>(idle_diff) / total_diff);
}

// 线程函数，模拟50%的CPU占用率
void worker(std::atomic<bool>& running) {
    while (running) {
        // 计算一段时间（占用CPU）
        auto start = std::chrono::steady_clock::now();
        while (std::chrono::steady_clock::now() - start < std::chrono::milliseconds(500));

        // 睡眠一段时间（释放CPU）
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}

// 打印CPU占用率的线程函数
void print_cpu_usage(std::atomic<bool>& running) {
    std::vector<unsigned long long> prev_times = read_cpu_times();

    while (running) {
        std::this_thread::sleep_for(std::chrono::seconds(1)); // 每秒打印一次

        std::vector<unsigned long long> curr_times = read_cpu_times();
        double cpu_usage = calculate_cpu_usage(prev_times, curr_times);

        std::cout << "CPU Usage: " << std::fixed << std::setprecision(2) << cpu_usage << "%" << std::endl;

        prev_times = curr_times;
    }
}

int main() {
    // 获取CPU核心数
    unsigned int num_cores = get_cpu_cores();
    std::cout << "Number of CPU cores: " << num_cores << std::endl;

    // 原子变量，用于控制线程的运行
    std::atomic<bool> running(true);

    // 创建线程池，每个核心一个线程，模拟50%的CPU占用率
    std::vector<std::thread> threads;
    for (unsigned int i = 0; i < num_cores; ++i) {
        threads.emplace_back(worker, std::ref(running));
    }

    // 启动打印CPU占用率的线程
    std::thread cpu_monitor(print_cpu_usage, std::ref(running));

    // 主线程等待用户输入以停止程序
    std::cout << "Press Enter to stop..." << std::endl;
    std::cin.get();

    // 停止所有线程
    running = false;
    for (auto& t : threads) {
        t.join();
    }
    cpu_monitor.join();

    std::cout << "Program stopped." << std::endl;
    return 0;
}